<!-- 部门配置 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top topSubmitBtn">
        <el-button class="btn" type="primary" @click="addDepartment()" >添加部门</el-button>
      </div>
      <div>
        <el-table 
          border 
          :data="tableData" 
          style="width: 100%; margin: 15px 0" 
          row-key="ID"  
          default-expand-all 
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column prop="date" type="index" label="序号" width="80" ></el-table-column>
          <el-table-column prop="DepartmentName" label="部门名称" ></el-table-column>
          <el-table-column label="操作"  width="80px">
            <template slot-scope="scope">
              <!-- <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button> -->
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape=false
      title="添加部门"
      :visible.sync="dialogVisible"
      v-el-drag-dialog
      width="30%">
      <el-form label-width="100px" :model="departForm" :rules="rules" ref="departForm">
        <!-- <el-form-item label='上级部门:'>
          <el-cascader
            ref="cascaderAddr"
            style="width:100%;"
            v-model="departForm.lastDepartmemt"
            placeholder="请选择部门，若空则为根部门"
            clearable
            :show-all-levels="false"
            :options="options"
            :props="{ expandTrigger: 'hover',  label: 'DepartmentName', value: 'ID'}"
            @change="handleChange">
          </el-cascader>
        </el-form-item> -->
        <el-form-item label='部门名称:' prop="departName">
          <el-input v-model.trim="departForm.departName" maxlength="16"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from "@/api/firstPage";
import { treeing, getTreeData } from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  data() {
    return {
      dialogVisible: false,
      departForm:{},
      options:[],
      tableData: [],
      rules:{
        departName: [
          { required: true, message: '部门名称不能为空' }
        ],
      }
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},
  methods: {
    async getData(){
      const res = await connrequest('GetDepartment')
      let arr = getTreeData(treeing(res.Data,'ID','ParentID'))
      this.tableData = arr
    },
    addDepartment(){
      this.departForm = {}
      this.ParentID = 0
      this.ParentName = []
      this.options = this.tableData
      this.$nextTick(()=>{
        this.$refs['departForm'].clearValidate()
      })
      this.dialogVisible = true
    },
    handleEdit(item){
      this.$message.info('该功能还在开发中')
      return
      this.options = this.tableData
      this.$set(this.departForm, 'lastDepartmemt', item.ID)
      this.$set(this.departForm, 'departName', item.DepartmentName)
      this.dialogVisible = true
    },
    handleChange(item){
      if(item){
        this.ParentID  = item[item.length - 1]
        this.ParentName = this.$refs['cascaderAddr'].getCheckedNodes()[0].label
      }
    },
    // 判断部门不能重复，但是子部门可以重复
    // isDuplicateDepartment(departmentName, parentId) {
    //   const children = this.tableData.filter(
    //     (department) => department.ParentID === parentId
    //   );
    //   if (
    //     children.some(
    //       (department) =>
    //         department.DepartmentName.toLowerCase() === departmentName.toLowerCase()
    //     )
    //   ) {
    //     return true; // 部门名称已存在
    //   }
    //   return false; // 部门名称不存在重复
    // },
    async submit(){
      this.$refs['departForm'].validate( async(valid) => {
        if(valid){
          if(!this.departForm.departName){
            this.$message.info("部门名称不能为空");
            return false
          }
          if (this.tableData.filter(item => item.DepartmentName === this.departForm.departName).length !== 0) {
            this.$message.info("部门已经存在");
            return false
          }
          const data = { 
            Data:{
              ID: 0,
              DepartmentName: this.departForm.departName,
              ParentID: this.ParentID,
              ParentName: this.ParentName
            }
          }
          const res = await connrequest('AddDepartment', data)
          if(res.Status.StatusCode === 0){
            this.$message({
              type: 'success',
              message: '部门添加成功'
            });
            this.getData()
            this.dialogVisible = false
          }
        }
      })
    },
    handleDelete(item){
      this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {
          Data:{
            ParentID: 0,
            ID: item.ID,
            DepartmentName: item.DepartmentName,
          }
        }
        const res = await connrequest('DelDepartment', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    }
  }
};
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>